/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chat.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 *
 * @author cibervn
 */
public class Camarero implements Runnable {

    private String clientName;
    private Manager manager;
    private PrintWriter pw;
    private BufferedReader br;

    public Camarero(String clientName, Manager manager, Socket socket) throws IOException {
        this.clientName = clientName;
        this.manager = manager;
        pw = new PrintWriter(socket.getOutputStream());
        br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    @Override
    public void run() {
        while (true) {
            while (true) {
                try {
                    //Try receive message from client
                    String[] parts = br.readLine().split(":");
                    if (parts.length != 2) {
                        //TODO: need to check more
                        continue;
                    }
                    String to = parts[0];
                    String msg = parts[1];

                    //Send received message to client other
                    manager.send(clientName, to, msg);
                } catch (Exception ex) {
                }
            }
        }
    }

    /**
     * Receive message from other client and send to client
     */
    public void receive(String from, String msg) {
        pw.println(from+":"+msg);
        pw.flush();
    }

    public String getClientName() {
        return clientName;
    }
    
}
